//
//  PriceTableViewController.m
//  CarWorld
//
//  Created by 曹杨杨 on 15/3/27.
//  Copyright (c) 2015年 CarWorldTeam. All rights reserved.
//

#import "PriceTableViewController.h"
#import "PriceDetailViewController.h"
#import "PriceCell.h"
#import "PriceListData.h"

#define CELLHEIGHT 80

@interface PriceTableViewController ()
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, retain) NSMutableArray *priceArray;
@end

@implementation PriceTableViewController
-(void)dealloc
{
    [_priceArray release];
    [super dealloc];
}
- (void)addRefurbish
{
    self.activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
    CGFloat px = [UIScreen mainScreen].bounds.size.width/2-50;
    _activityIndicator.frame = CGRectMake(px, 100, 100, 50);
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 20)];
    lbl.text = @"玩命加载中...";
    lbl.font = [UIFont systemFontOfSize:10];
    lbl.textAlignment = NSTextAlignmentCenter;
    [_activityIndicator addSubview:lbl];
    [lbl     release];
    [_activityIndicator startAnimating];
    [self.view addSubview:_activityIndicator];
    self.view.userInteractionEnabled = NO;
    
}
- (void)stopAnimating
{
    [_activityIndicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

- (void)getNewURL
{
    [self addRefurbish];
    NSURL *url = [NSURL URLWithString:@"http://mobile.auto.sohu.com/mcms/external/getNews.at?cityCode=310000&newsType=2&pageSize=20"];
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:requst queue:[[[NSOperationQueue alloc] init] autorelease] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            [self parisData:data];
        }
    }];
}


- (void)parisData:(NSData *)data
{
    if (data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers error:nil];
            NSArray *array = dic[@"RESULT"];
            self.priceArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                PriceListData *cellData = [[PriceListData alloc] init];
                [cellData setValuesForKeysWithDictionary:dic];
                [_priceArray addObject:cellData];
                [cellData release];
            }
          
//            [self.tableView reloadData];
//            [self stopAnimating];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self stopAnimating];
        });
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.title = @"最新行情";
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self getNewURL];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // Return the number of rows in the section.
    return _priceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"price";
    PriceCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[PriceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier height:CELLHEIGHT];
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
    PriceListData *cellData = _priceArray[indexPath.row];
    if (cellData.image == nil) {
        [cellData addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:[indexPath retain]];
    }
    
    cell.cellData = cellData;
    return cell;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSIndexPath *indexPath = (NSIndexPath *)context;
    NSArray *array = [self.tableView indexPathsForVisibleRows];
    if ([array containsObject:indexPath]) {
        PriceCell *cell = (PriceCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        UIImage *image = (UIImage *)[change objectForKey:@"new"];
        cell.image_View.image = image;
    }
    [indexPath release];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    PriceDetailViewController *priceDetail = [[PriceDetailViewController alloc] init];
//    priceDetail.priceId = [_priceArray[indexPath.row] Id];
//    [self.navigationController pushViewController:priceDetail animated:YES];
//    [priceDetail release];
    
    
    /*
     UIModalTransitionStyleCoverVertical=0, //默认方式，竖向上推
     UIModalTransitionStyleFlipHorizontal, //水平反转
     UIModalTransitionStyleCrossDissolve,//隐出隐现
     UIModalTransitionStylePartialCurl,//部分翻页效果
     */
        PriceDetailViewController *priceDetail = [[PriceDetailViewController alloc] init];
        priceDetail.priceId = [_priceArray[indexPath.row] Id];
    
    UINavigationController *priceNVC = [[UINavigationController alloc] initWithRootViewController:priceDetail];
    [priceNVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
        [self presentViewController:priceNVC animated:YES completion:^{
        
        }];
        [priceDetail release];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
